<template>
	<view class="profile-edit-container" :style="containerStyle">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar" :style="{ paddingTop: safeDistance + 'px' }">
			<view class="navbar-content">
				<view class="nav-left" @click="goBack">
					<uni-icons type="left" size="24" color="#fff"></uni-icons>
					<text class="nav-back-text">返回</text>
				</view>
				<text class="nav-title">编辑个人信息</text>
				<view class="nav-right" @click="saveProfile">
					<text class="nav-save-text">保存</text>
				</view>
			</view>
		</view>

		<!-- 主要内容区域 -->
		<scroll-view class="content-scroll" scroll-y show-scrollbar="false" :style="{ paddingTop: (safeDistance + 60) + 'px' }">
			<!-- 头像编辑区域 -->
			<view class="avatar-edit-section">
				<view class="avatar-container">
					<!-- 显示当前头像 -->
					<view class="current-avatar" v-if="form.avatar">
						<image :src="getAvatarUrl(form.avatar)" 
							class="user-avatar" mode="aspectFill"
							@error="onImageError"
							@load="onImageLoad"></image>
					</view>
					<view v-else class="default-avatar">
						<text class="avatar-text">{{ getAvatarText() }}</text>
					</view>
					
					<!-- 调试信息 -->
					<view v-if="form.avatar" class="debug-info" style="position: absolute; bottom: -50px; left: 0; font-size: 12px; color: #666;">
						<text>Avatar: {{ form.avatar || '' }}</text>
						<text>URL: {{ getAvatarUrl(form.avatar || '') }}</text>
					</view>
					
					<!-- 文件选择器（隐藏） -->
					<uni-file-picker limit="1" :del-icon="false" :disable-preview="true" :imageStyles="hiddenAvatarStyles"
						v-model="avatar" file-mediatype="image" @select="handleAvatarSelect" class="hidden-picker">
					</uni-file-picker>
					
					<!-- 点击遮罩层 -->
					<view class="avatar-edit-overlay" @click="triggerFilePicker">
						<text class="edit-icon">📷</text>
						<text class="edit-text">更换头像</text>
					</view>
				</view>
			</view>

			<!-- 表单编辑区域 -->
			<view class="form-section">
				<!-- 昵称输入 -->
				<view class="form-item">
					<view class="form-label">
						<text class="label-text">昵称</text>
						<text class="label-required">*</text>
					</view>
					<view class="form-input-wrapper">
						<input 
							v-model="form.nickname" 
							class="form-input" 
							placeholder="请输入昵称"
							maxlength="20"
							:style="{ color: themeStyles.textPrimary }"
						/>
						<text class="input-count">{{ (form.nickname || '').length }}/20</text>
					</view>
					<text class="form-hint">昵称将在个人资料中显示</text>
				</view>

				<!-- 用户名显示（不可编辑） -->
				<view class="form-item">
					<view class="form-label">
						<text class="label-text">用户名</text>
					</view>
					<view class="form-input-wrapper readonly">
						<text class="readonly-text" :style="{ color: themeStyles.textSecondary }">{{ form.username }}</text>
						<text class="readonly-hint">用户名不可修改</text>
					</view>
				</view>

				<!-- 邮箱输入 -->
				<view class="form-item">
					<view class="form-label">
						<text class="label-text">邮箱</text>
					</view>
					<view class="form-input-wrapper">
						<input 
							v-model="form.email" 
							class="form-input" 
							placeholder="请输入邮箱地址"
							type="email"
							:style="{ color: themeStyles.textPrimary }"
						/>
					</view>
					<text class="form-hint">用于接收重要通知和找回密码</text>
				</view>

				<!-- 手机号输入 -->
				<view class="form-item">
					<view class="form-label">
						<text class="label-text">手机号</text>
					</view>
					<view class="form-input-wrapper">
						<input 
							v-model="form.phone" 
							class="form-input" 
							placeholder="请输入手机号"
							type="number"
							maxlength="11"
							:style="{ color: themeStyles.textPrimary }"
						/>
					</view>
					<text class="form-hint">用于账户安全验证</text>
				</view>
			</view>

			<!-- 保存按钮 -->
			<view class="save-section">
				<button class="save-btn" @click="saveProfile" :disabled="loading">
					<text class="save-btn-text">{{ loading ? '保存中...' : '保存修改' }}</text>
				</button>
			</view>
		</scroll-view>
	</view>
</template>

<script setup lang="ts">
	import { ref, computed, onMounted } from 'vue';
	import { getThemeStyles } from '@/stores/theme';
	import { getUserInfoAPI, updateUserInfoAPI, uploadAvatarAPI, updateAvatarAPI } from '@/services/user';
	import type { UserInfoResult, AvatarUploadResult } from '@/types';
	import { baseURL } from '@/utils/config';


	//获取头像url	
	const getAvatarUrl = (avatar : string) => {
		if (!avatar) return '';
		// 如果已经是完整URL，直接返回
		if (avatar.startsWith('http')) {
			return avatar;
		}
		// 如果是相对路径，拼接baseURL
		return avatar.startsWith('/') ? baseURL + avatar : baseURL + '/' + avatar;
	}

	/**
	 * 安全距离
	 */
	const safeDistance = computed(() => {
		const systemInfo = uni.getSystemInfoSync();
		const safeAreaTop = systemInfo.safeAreaInsets?.top || 0;
		return safeAreaTop + 10;
	});

	/**
	 * 表单数据
	 */
	const form = ref<UserInfoResult>({
		nickname: '',
		username: '',
		avatar: '',
		phone: '',
		email: ''
	});

	/**
	 * 加载状态
	 */
	const loading = ref(false);

	/**
	 * 头像数据
	 */
	const avatar = ref([]);

	/**
	 * 头像样式配置
	 */
	const avatarStyles = {
		width: '120rpx',
		height: '120rpx',
		border: {
			radius: '60rpx'
		}
	};

	/**
	 * 隐藏的文件选择器样式配置
	 */
	const hiddenAvatarStyles = {
		width: '0rpx',
		height: '0rpx',
		border: {
			radius: '0rpx'
		}
	};

	/**
	 * 主题样式
	 */
	const themeStyles = computed(() => getThemeStyles());

	/**
	 * 容器背景样式
	 */
	const containerStyle = computed(() => ({
		background: themeStyles.value.bgGradient
	}));

	/**
	 * 获取头像文字
	 */
	const getAvatarText = () => {
		const nickname = form.value.nickname || '';
		if (nickname && nickname.length > 0) {
			return nickname.charAt(0).toUpperCase();
		}
		return 'U';
	};

	/**
	 * 返回上一页
	 */
	const goBack = () => {
		uni.navigateBack();
	};

	/**
	 * 触发文件选择器
	 */
	const triggerFilePicker = () => {
		// 通过程序触发uni-file-picker的选择
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: (res: any) => {
				// 模拟uni-file-picker的数据格式
				const fileData = {
					tempFiles: [{
						tempFilePath: res.tempFilePaths[0],
						path: res.tempFilePaths[0]
					}]
				};
				handleAvatarSelect(fileData);
			}
		});
	};

	/**
	 * 处理头像选择
	 * @param {any} file 选择的文件信息
	 */
	const handleAvatarSelect = (file: any) => {
		console.log('选择的头像文件:', file);
		// 检查是否有选择文件
		if (file && file.tempFiles && file.tempFiles.length > 0) {
			// 调用上传函数
			uploadAvatarAPI(file.tempFiles[0].tempFilePath || file.tempFiles[0].path).then(response => {
				handleAvatarUploadSuccess(response);
			}).catch(error => {
				handleAvatarUploadFail(error);
			});
		}
	};

	/**
	 * 处理头像上传成功
	 * @param {AvatarUploadResult} response 上传成功的响应信息
	 */
	const handleAvatarUploadSuccess = (response: AvatarUploadResult) => {
		console.log('头像上传成功:', response);
		try {
			// 更新头像URL
			if (response && response.url) {
				// 更新表单数据
				form.value.avatar = response.url;
				
				// 更新用户头像到后端
				updateAvatarAPI(response.url);

				// 可以在这里更新用户存储中的头像信息
				uni.showToast({
					title: '头像上传成功',
					icon: 'success'
				});
			} else {
				throw new Error('响应数据格式不正确');
			}
		} catch (error) {
			console.error('处理上传成功响应失败:', error);
			handleAvatarUploadFail(error);
		}
	};

	/**
	 * 处理头像上传失败
	 * @param {any} error 上传失败的错误信息
	 */
	const handleAvatarUploadFail = (error: any) => {
		console.error('头像上传失败:', error);
		uni.showToast({
			title: '头像上传失败，请重试',
			icon: 'none'
		});
	};

	/**
	 * 验证表单
	 */
	const validateForm = () => {
		if (!form.value.nickname.trim()) {
			uni.showToast({
				title: '请输入昵称',
				icon: 'none',
				duration: 2000
			});
			return false;
		}

		if (form.value.email && !isValidEmail(form.value.email)) {
			uni.showToast({
				title: '请输入正确的邮箱格式',
				icon: 'none',
				duration: 2000
			});
			return false;
		}

		if (form.value.phone && !isValidPhone(form.value.phone)) {
			uni.showToast({
				title: '请输入正确的手机号格式',
				icon: 'none',
				duration: 2000
			});
			return false;
		}

		return true;
	};

	/**
	 * 验证邮箱格式
	 */
	const isValidEmail = (email: string) => {
		const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
		return emailRegex.test(email);
	};

	/**
	 * 验证手机号格式
	 */
	const isValidPhone = (phone: string) => {
		const phoneRegex = /^1[3-9]\d{9}$/;
		return phoneRegex.test(phone);
	};

	/**
	 * 保存个人信息
	 */
	const saveProfile = async () => {
		if (!validateForm()) {
			return;
		}

		loading.value = true;
		try {
			uni.showLoading({
				title: '保存中...',
				mask: true
			});

			// 调用更新用户信息API
			await updateUserInfoAPI(form.value);

			uni.hideLoading();
			uni.showToast({
				title: '保存成功',
				icon: 'success',
				duration: 2000
			});


			// 延迟返回上一页
			setTimeout(() => {
				uni.navigateBack();
			}, 2000);

		} catch (error) {
			uni.hideLoading();
			uni.showToast({
				title: '保存失败',
				icon: 'none',
				duration: 2000
			});
			console.error('保存个人信息失败:', error);
		} finally {
			loading.value = false;
		}
	};

	/**
	 * 加载用户信息
	 */
	const loadUserInfo = async () => {
		try {
			const res = await getUserInfoAPI();
			if (res.data) {
				// 确保所有字段都有默认值，避免null值
				form.value = {
					nickname: res.data.nickname || '',
					username: res.data.username || '',
					avatar: res.data.avatar || '',
					phone: res.data.phone || '',
					email: res.data.email || ''
				};
			}
		} catch (error) {
			console.error('获取用户信息失败:', error);
			uni.showToast({
				title: '获取用户信息失败',
				icon: 'none',
				duration: 2000
			});
		}
	};

	/**
	 * 图片加载成功
	 */
	const onImageLoad = () => {
		console.log('头像图片加载成功');
	};

	/**
	 * 图片加载失败
	 */
	const onImageError = (e: any) => {
		console.error('头像图片加载失败:', e);
		console.log('当前头像URL:', getAvatarUrl(form.value.avatar));
	};

	/**
	 * 页面初始化
	 */
	onMounted(() => {
		loadUserInfo();
		
		// 监听键盘弹出和收起事件，防止页面偏移
		uni.onKeyboardHeightChange((res) => {
			console.log('键盘高度变化:', res.height);
			// 可以在这里添加额外的处理逻辑
		});
	});
</script>

<style lang="scss" scoped>
	.profile-edit-container {
		min-height: 100vh;
		position: relative;
		width: 100%;
		overflow-x: hidden; /* 防止水平滚动 */
	}

	/* 自定义导航栏 */
	.custom-navbar {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		width: 100%;
		z-index: 1000;
		background: rgba(255, 255, 255, 0.95);
		backdrop-filter: blur(10px);
		border-bottom: 1px solid rgba(0, 0, 0, 0.1);

		.navbar-content {
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 60rpx;
			padding: 0 32rpx;
			width: 100%;
			box-sizing: border-box;

			.nav-left {
				display: flex;
				align-items: center;
				gap: 8rpx;
				cursor: pointer;

				.nav-back-text {
					font-size: 28rpx;
					color: v-bind('themeStyles.primaryColor');
				}
			}

			.nav-title {
				font-size: 32rpx;
				font-weight: 600;
				color: v-bind('themeStyles.textPrimary');
			}

			.nav-right {
				cursor: pointer;

				.nav-save-text {
					font-size: 28rpx;
					color: v-bind('themeStyles.primaryColor');
					font-weight: 500;
				}
			}
		}
	}

	/* 内容滚动区域 */
	.content-scroll {
		height: 100vh;
		padding: 0 32rpx 40rpx;
		width: 100%;
		box-sizing: border-box;
		position: relative;
	}

	/* 头像编辑区域 */
	.avatar-edit-section {
		display: flex;
		justify-content: center;
		padding: 60rpx 0;

		.avatar-container {
			position: relative;
			width: 160rpx;
			height: 160rpx;
			border-radius: 50%;
			overflow: hidden;
			cursor: pointer;

			.user-avatar {
				width: 100%;
				height: 100%;
				border-radius: 50%;
			}

			.default-avatar {
				width: 100%;
				height: 100%;
				background: v-bind('themeStyles.primaryGradient');
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 50%;

				.avatar-text {
					font-size: 48rpx;
					font-weight: 600;
					color: #fff;
				}
			}

			.hidden-picker {
				position: absolute;
				top: -9999rpx;
				left: -9999rpx;
				opacity: 0;
				pointer-events: none;
			}

			.current-avatar {
				width: 100%;
				height: 100%;
				border-radius: 50%;
				overflow: hidden;
			}

			.avatar-edit-overlay {
				position: absolute;
				bottom: 0;
				left: 0;
				right: 0;
				background: rgba(0, 0, 0, 0.6);
				color: #fff;
				text-align: center;
				padding: 8rpx 0;
				font-size: 20rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				gap: 4rpx;
				cursor: pointer;

				.edit-icon {
					font-size: 24rpx;
				}

				.edit-text {
					font-size: 18rpx;
				}
			}
		}
	}

	/* 表单区域 */
	.form-section {
		width: 100%;
		
		.form-item {
			margin-bottom: 48rpx;
			width: 100%;

			.form-label {
				display: flex;
				align-items: center;
				margin-bottom: 16rpx;

				.label-text {
					font-size: 28rpx;
					font-weight: 500;
					color: v-bind('themeStyles.textPrimary');
				}

				.label-required {
					color: #ff4757;
					margin-left: 4rpx;
					font-size: 28rpx;
				}
			}

			.form-input-wrapper {
				position: relative;
				background: rgba(255, 255, 255, 0.9);
				border-radius: 16rpx;
				border: 2rpx solid v-bind('themeStyles.borderLight');
				transition: all 0.3s ease;
				width: 100%;
				box-sizing: border-box;

				&:focus-within {
					border-color: v-bind('themeStyles.primaryColor');
					box-shadow: 0 0 0 4rpx rgba(99, 102, 241, 0.1);
					transform: none; /* 防止聚焦时的位移 */
				}

				&.readonly {
					background: rgba(0, 0, 0, 0.05);
					border-color: transparent;
					min-height: 88rpx;
					display: flex;
					align-items: center;

					.readonly-text {
						padding: 32rpx 32rpx;
						font-size: 30rpx;
						display: block;
						width: 100%;
						box-sizing: border-box;
						line-height: 1.4;
					}

					.readonly-hint {
						position: absolute;
						right: 32rpx;
						top: 50%;
						transform: translateY(-50%);
						font-size: 24rpx;
						color: v-bind('themeStyles.textPlaceholder');
					}
				}

				.form-input {
					width: 100%;
					padding: 32rpx 32rpx;
					font-size: 30rpx;
					border: none;
					background: transparent;
					box-sizing: border-box;
					outline: none;
					min-height: 88rpx;
					line-height: 1.4;
					display: flex;
					align-items: center;

					&::placeholder {
						color: v-bind('themeStyles.textPlaceholder');
					}

					&:focus {
						outline: none;
						transform: none; /* 防止聚焦时的位移 */
					}
				}

				.input-count {
					position: absolute;
					right: 32rpx;
					top: 50%;
					transform: translateY(-50%);
					font-size: 26rpx;
					color: v-bind('themeStyles.textPlaceholder');
					background: rgba(255, 255, 255, 0.8);
					padding: 4rpx 8rpx;
					border-radius: 8rpx;
				}
			}

			.form-hint {
				margin-top: 12rpx;
				font-size: 24rpx;
				color: v-bind('themeStyles.textPlaceholder');
				padding-left: 8rpx;
			}
		}
	}

	/* 保存按钮区域 */
	.save-section {
		padding: 40rpx 0;

		.save-btn {
			width: 100%;
			background: v-bind('themeStyles.primaryGradient');
			border: none;
			border-radius: 50rpx;
			padding: 32rpx 0;
			box-shadow: v-bind('themeStyles.buttonBoxShadow');
			transition: all 0.3s ease;

			&:active {
				transform: translateY(2rpx);
				box-shadow: v-bind('themeStyles.cardBoxShadow');
			}

			&:disabled {
				opacity: 0.6;
				transform: none;
			}

			.save-btn-text {
				color: #fff;
				font-size: 32rpx;
				font-weight: 600;
				letter-spacing: 4rpx;
			}
		}
	}
</style>
